<?php
namespace app\controller;

use AlibabaCloud\SDK\Dingtalk\Vedu_1_0\Models\BatchCreateRequest\data;
use app\BaseController;
use app\controller\model\Tables;
use liliuwei\think\Auth;
use think\facade\Session;
use think\facade\Db;
class Users extends BaseController
{
    protected $getpath="";
    protected $gobaluser="";
    protected $tables;
    public function __construct($check=true){
	    $check?checkuser():'';
        $this->gobaluser=Session::get("uid");
        $this->tables = new Tables();
    }
	public function rechargeAdmin(){
		return view("users/rechargeAdmin");
	}
	public function setUserLevelLog($user=[]){
		if(!$user)return false;
		$insert = DB::name($this->tables->agentUserLog)->insert([
			'uid'=>$user['id'],
			'username'=>$user['username'],
			'level'=>$user['level'],
			'code'=>$user['addressCode'],
			'levelStr'=>$user['levelStr'],
			'addTime'=>nowTime(),
			'addDate'=>nowDate(),
		]);
		return $insert;
	}
	public function realMeAdminSave(){
		$this->setDisable();
	}
	public function realMeAdmin(){
		$userID = request()->param("id");
		$re=[];
		if($userID>0){
			$re = DB::name($this->tables->users)->where("id",$userID)->find();
			$re['amount']='';
		}else{
			echojson([],1,'ID错误');
		}
		if($re['carImg'] && strlen($re['carImg'])>10){
			$re['imgArr']=explode(",",$re['carImg']);
		}else{
			$re['imgArr']=['',''];
		}
		return view("users/realMeAdmin")->assign(['data'=>$re]);
	}
	public function realMe(){
		$classModel = new \app\controller\model\Classes();
		return view("realMe")->assign(['cid'=>$classModel->rClassessToOption(145)]);
	}
	public function setDisable(){
		$userID = request()->param("userID");
		$status = request()->param("status");
		$content = request()->param("content");
		if(!$user = rusers($userID))echojson([],1,'ID错误');
		if($status==2){
			$up = DB::name($this->tables->users)->where("id",$userID)->update(['status'=>2,'content'=>$content]);
		}else{
			$up = DB::name($this->tables->users)->where("id",$userID)->update(['status'=>-1,'content'=>$content]);
		}
		if($up){
			echojson();
		}
		echojson([],1,'修改失败');
	}
	public function setUserLevel(){
		$level = request()->param("level");
		$userID = request()->param("userID");
		if(!in_array($level,[0,236,247,248])) echojson([],1,'等级错误');
		if(!$user = rusers($userID))echojson([],1,'ID错误');
		if($level==0){
			$levelStr="游客";
		}else{
			$levelStr = r_rule2($level)['title'];
		}
		$admin = r_user($this->gobaluser);
		$up = DB::name($this->tables->users)->where("id",$userID)->update(['level'=>$level,'levelStr'=>$levelStr,'levelTime'=>date('Y-m-d',strtotime("+1 year"))]);
		if($up){
			DB::name($this->tables->levelLog)->insert(['uid'=>$userID,'username'=>$user['username'],'nickname'=>$user['nickname'],'adminName'=>$admin['fullname'],'admin'=>$this->gobaluser,'level'=>$level,'levelStr'=>$levelStr,'addTime'=>nowTime()]);
			echojson();
		}
		echojson([],1,'修改失败');
	}
	public function rechargeAdminSave(){
		$id = request()->param("id");
		lock();
		$log = DB::name($this->tables->amountYB)->where("id",$id)->lock(true)->find();
		if($log && $log['status']==0){
			$user = rusers($log['uid']);
			if(!$user)echojson([],1,'充值用户错误');
			$amountEnd = bcadd($user['amountYB'],$log['amount'],2);
			$up = ['admin2'=>$this->gobaluser,'amountStart'=>$user['amountYB'],'amountEnd'=>$amountEnd,'adminTime'=>nowTime(),'status'=>1];
			$re = DB::name($this->tables->amountYB)->where("id",$id)->update($up);
			if(!$re) echojson([],1,'添加失败:1');
			$userUp = DB::name($this->tables->users)->where("id",$log['uid'])->update(['amountYB'=>$amountEnd]);
			if(!$userUp) echojson([],1,'添加失败:2');
            if($user['level']<236){
                $userUp = DB::name($this->tables->users)->where("id",$log['uid'])->update(['level'=>236,'levelStr'=>'用户']);
                if(!$userUp) echojson([],1,'添加失败:2');
            }
			echojson();
		}
		echojson([],1,'订单错误');
	}
	public function rechargeAdminList(){
		$page = request()->param("page");
		$username = request()->param("username");
		$username2 = request()->param("username2");
		$mobile = request()->param("mobile");
		$mobile2 = request()->param("mobile2");
		$admin = request()->param("admin");
		$admin2 = request()->param("admin2");
		$status = request()->param("status");
		$limit = request()->param("limit");
		$where="1=1";
		if($username!=''){
			$users = DB::name($this->tables->users)->where("username","like","%$username%")->column("id");
			if($users){
				if(count($users)>50) echojson([],1,'关键词太短');
				$where .= " and uid in (".implode(",",$users).")";
			}else{
				$where .= " and uid < 0";
			}
		}
		if($mobile!=''){
			$users = DB::name($this->tables->users)->where("mobile","like","%$mobile%")->column("id");
			if($users){
				if(count($users)>50) echojson([],1,'关键词太短');
				$where .= " and uid in (".implode(",",$users).")";
			}else{
				$where .= " and uid < 0";
			}
		}
		if($username2!=''){
			$users = DB::name($this->tables->users)->where("username","like","%$username2%")->column("id");
			if($users){
				if(count($users)>50) echojson([],1,'关键词太短');
				$where .= " and fromID in (".implode(",",$users).")";
			}else{
				$where .= " and fromID < 0";
			}
		}
		if($mobile2!=''){
			$users = DB::name($this->tables->users)->where("$mobile2","like","%$mobile2%")->column("id");
			if($users){
				if(count($users)>50) echojson([],1,'关键词太短');
				$where .= " and fromID in (".implode(",",$users).")";
			}else{
				$where .= " and fromID < 0";
			}
		}
		if($admin>0){
			$where .= " and admin = $admin";
		}
		if($admin2>0){
			$where .= " and admin2 = $admin2";
		}
		if($status != ''){
			$where .= " and status = $status";
		}
		$list = getpagedata($this->tables->amountYB,"",true,$where);
		$count = $list[1];
		$list = $list[0]->all();
		$admins = r_users();
		$pays = r_classes(240);
		foreach ($list as $k => $v){
			$list[$k]['uid'] = userIDToUserName($v['uid']);
			$list[$k]['fromID'] = userIDToUserName($v['fromID']);
			$list[$k]['admin'] = adminIDToUserName($admins,$v['admin']);
			$list[$k]['admin2'] = adminIDToUserName($admins,$v['admin2']);
			$list[$k]['pays'] = rclasstitle($pays,$v['pays']);
		}
		pagejson($list,0,'',$count);
	}
	public function rechargeAdmin2Save($data=[]){
		isset($data['userID']) && $data['userID']>0?$userID=$data['userID']:$userID = request()->param("userID");
		isset($data['img1']) && $data['img1']!=''?$img=$data['img1']:$img = request()->param("img");
		isset($data['amount']) && $data['amount']!=''?$amount=$data['amount']:$amount = request()->param("amount");
		isset($data['pays']) && $data['pays']!=''?$pays=$data['pays']:$pays = request()->param("pays");
		if($userID<1 || $img=='' || abs($amount)==0 || $pays<1) echojson([],1,"所有项必填");
		lock();
		$user = DB::name($this->tables->users)->where("id",$userID)->lock(true)->find();
		if(!$user) echojson([],1,'ID错误');
		$amountEnd = bcadd($user['amountYB'],$amount,2);
		$up = ['admin'=>$this->gobaluser,'pays'=>$pays,'uid'=>$userID,'fromID'=>0,'amount'=>$amount,'amountStart'=>$user['amountYB'],'amountEnd'=>$amountEnd,'addTime'=>nowTime(),'img'=>$img,'title'=>'会员充值'];
		isset($data['addDate']) && isset($data['addTime'])?$up['addTime']=$data['addDate']." ".$data['addTime']:'';
		isset($data['fromUID']) && $data['fromUID']==1?$up['fromUID']=$data['fromUID']:'';
		$re = DB::name($this->tables->amountYB)->insert($up);
		if(!$re) echojson([],1,'添加失败:1');
		//审核生效 status 0 到1
//		$userUp = DB::name($this->tables->users)->where("id",$userID)->update(['amountYB'=>$amountEnd]);
//		if(!$userUp) echojson([],1,'添加失败:2');
		echojson();
	}
    public function list(){
        $classModel = new \app\controller\model\Classes();
        return view()->assign(['levels'=>$classModel->rClassessToOption(235)]);
    }
    public function levelLog(){
        $classModel = new \app\controller\model\Classes();
        return view("levelLog")->assign(['levels'=>$classModel->rClassessToOption(235)]);
    }
    public function study(){
        $classModel = new \app\controller\model\Classes();
        return view()->assign(['cid'=>$classModel->rClassessToOption(145)]);
    }
    public function userAdd(){
        $id = request()->param("id");
        $re=[];
        $selectCid = 0;
        $selectGid = 0;
        if($id>0){
            $re = DB::name($this->tables->users)->where("id",$id)->find();
        }
        return view("users/adduser")->assign(['data'=>$re]);
    }
    public function rechargeAdmin2(){
        $userID = request()->param("userID");
        $re=[];
        if($userID>0){
            $re = DB::name($this->tables->users)->where("id",$userID)->find();
	        $re['amount']='';
        }else{
			echojson([],1,'ID错误');
        }
	    $classModel = new \app\controller\model\Classes();
        return view("users/rechargeAdmin2")->assign(['data'=>$re,'pays'=>$classModel->rClassessToOption(240)]);
    }
    public function studyAdd(){
        $id = request()->param("id");
        $re=[];
        $selectCid = 0;
        $selectGid = 0;
        if($id>0){
            $re = DB::name($this->tables->users)->where("id",$id)->find();
            if($re){
                $selectCid = $re['cid'];
                $selectGid = $re['gid'];
                $re['files']=$re['files2'];
                unset($re['files2']);
            }
        }
        $classModel = new \app\controller\model\Classes();
        return view("users/studyAdd")->assign(['user'=>$re,'cid'=>$classModel->rClassessToOption(145,$selectCid),'gid'=>$classModel->rWorkgroupToOption($selectGid)[0]]);
    }
    public function studySave(){
        $data = request()->param();
        $id=request()->param("id");
        if(isset($data['id']) && $data['id']>0){
            $id = $data['id'];
            unset($data['id']);
        }
        $up=false;
        if($id>0){
            //编辑模式
            $re = r_one($this->tables->users,"id=$id");
            if(!$re){echojson([],1,'ID错误');}
            $temarr['files2']=$data['files'];
            $temarr['study']=$data['status'];
            $up = DB::name($this->tables->users)->where("id",$id)->update($temarr);
        }
        if(!$up){echojson([],1,'操作失败');}
        echojson();
    }
    public function userSave(){
        $data = request()->param();
        $id=request()->param("id");
        if(isset($data['id']) && $data['id']>0){
            $id = $data['id'];
            unset($data['id']);
        }
        if($data['agentTime']=='') unset($data['agentTime']);
        if($data['levelTime']=='') unset($data['levelTime']);
        if($id>0){
            //编辑模式
            $re = r_one($this->tables->users,"id=$id");
            if(!$re){echojson([],1,'ID错误');}
            $up = DB::name($this->tables->users)->where("id",$id)->update($data);
        }else{
            $data['addtime']=nowTime();
            $up=DB::name($this->tables->users)->insert($data);
        }
        if(!$up){echojson([],1,'操作失败');}
        echojson();
    }
    public function isSureIDS(){
        $ids = request()->param("ids");
        $ids = json_decode($ids,true);
        if(!is_array($ids) || count($ids)<1){echojson([],1,'所选为空');}
        $re = DB::name($this->tables->users)->whereIn("id",$ids)->update(['insure'=>1]);
        if($re){
            echojson();
        }else{
            echojson([],1,'更新失败');
        }
    }
    public function setStatus(){
        $ids = request()->param("ids");
        $status = request()->param("status");
        $ids = json_decode($ids,true);
        if(!is_array($ids) || count($ids)<1){echojson([],1,'所选为空');}
        $re = DB::name($this->tables->users)->whereIn("id",$ids)->update(['status'=>$status]);
        if($re){
            echojson();
        }else{
            echojson([],1,'更新失败');
        }
    }
    public function studyIDS(){
        $ids = request()->param("ids");
        $img = request()->param("img");
        $ids = json_decode($ids,true);
        if($img==''){echojson([],1,'图片不可为空');}
        if(!is_array($ids) || count($ids)<1){echojson([],1,'所选为空');}
        $re = DB::name($this->tables->users)->whereIn("id",$ids)->update(['study'=>1,'files2'=>$img]);
        if($re){
            echojson();
        }else{
            echojson([],1,'更新失败');
        }
    }
    public function usersList($return =false,$postLimit=0){
        $page = request()->param("page");
        $nickname = request()->param("nickname");
	    $username = request()->param("username");
	    $openid = request()->param("openid");
        $status = request()->param("status");
        $limit = request()->param("limit");
        $sql = DB::name($this->tables->users)->alias("a");
        $limit < 10 ? $limit = 10 : '';
        if($postLimit>0){
            $limit = $postLimit ;
        }
        $page<1?$page=1:'';
        if($nickname!=''){
            $sql = $sql->where("a.nickname","like", "%$nickname%");
        }


	    if($username!=''){
		    $sql = $sql->where("a.username","like", "%$username%");
	    }

	    if($openid!=''){
		    $sql = $sql->where("a.openid",$openid);
	    }

        if($status!=''){
            $sql = $sql->where("a.status",$status);
        }
        $count = (clone $sql)->count();
        $pages = ceil($count / $limit);
        $pages < 1 ? $pages = 1 : '';
        $page > $pages ? $page = $pages : '';
        $res = $sql->order("a.id desc")->limit(($page - 1) * $limit, $limit)->select();
        if($return){
            return [$res, 0, '', $count];
        }
        pagejson($res, 0, '', $count);
    }
    public function levelLogList($return =false,$postLimit=0){
        $page = request()->param("page");
        $nickname = request()->param("nickname");
        $username = request()->param("username");
        $mobile = request()->param("mobile");
        $carID = request()->param("carID");
        $limit = request()->param("limit");
        $sql = DB::name($this->tables->levelLog);
        $limit < 10 ? $limit = 10 : '';
        if($postLimit>0){
            $limit = $postLimit ;
        }
        $page<1?$page=1:'';

	    if($username!=''){
		    $users = DB::name($this->tables->users)->where("username","like","%$username%")->column("id");
		    if($users){
			    if(count($users)>50) echojson([],1,'关键词太短');
			    $sql =$sql->whereIn('uid',$users);
		    }else{
			    $sql =$sql->where('uid',0);
		    }
	    }
	    if($nickname!=''){
		    $users = DB::name($this->tables->users)->where("nickname","like","%$nickname%")->column("id");
		    if($users){
			    if(count($users)>50) echojson([],1,'关键词太短');
			    $sql =$sql->whereIn('uid',$users);
		    }else{
			    $sql =$sql->where('uid',0);
		    }
	    }
	    if($mobile!=''){
		    $users = DB::name($this->tables->users)->where("mobile","like","%$mobile%")->column("id");
		    if($users){
			    if(count($users)>50) echojson([],1,'关键词太短');
			    $sql =$sql->whereIn('uid',$users);
		    }else{
			    $sql =$sql->where('uid',0);
		    }
	    }
	    if($carID!=''){
		    $users = DB::name($this->tables->users)->where("carID",$carID)->find();
		    if($users){
			    if(count($users)>50) echojson([],1,'关键词太短');
			    $sql =$sql->where('uid',$users['id']);
		    }else{
			    $sql =$sql->where('uid',0);
		    }
	    }

        $count = (clone $sql)->count();
        $pages = ceil($count / $limit);
        $pages < 1 ? $pages = 1 : '';
        $page > $pages ? $page = $pages : '';
        $res = $sql->order("id desc")->limit(($page - 1) * $limit, $limit)->select();
        if($return){
            return [$res, 0, '', $count];
        }
        pagejson($res, 0, '', $count);
    }
}
